package response

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// Unified response structure
type Response[T any] struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    T      `json:"data"`
}

// Success response with optional parameters
func Success[T any](ctx *gin.Context, message string, data T) {
	ctx.JSON(http.StatusOK, Response[T]{
		Code:    http.StatusOK,
		Message: message,
		Data:    data,
	})
}

// Error response with optional parameters
func Error[T any](ctx *gin.Context, code int, message string, data T) {
	// Map business error codes to corresponding HTTP status codes
	httpStatus := getHttpStatusFromCode(code)
	ctx.JSON(httpStatus, Response[T]{
		Code:    code,
		Message: message,
		Data:    data,
	})
}

// getHttpStatusFromCode returns corresponding HTTP status code based on business error code
func getHttpStatusFromCode(code int) int {
	switch code {
	case INVALID_PARAMS:
		return http.StatusBadRequest
	case UNAUTHORIZED:
		return http.StatusUnauthorized
	case FORBIDDEN:
		return http.StatusForbidden
	case NOT_FOUND:
		return http.StatusNotFound
	case ERROR, DATABASE_ERROR, CACHE_ERROR, FILE_OPER_ERROR:
		return http.StatusInternalServerError
	default:
		return http.StatusOK
	}
}
